package com.fulizhe.catlocal.integration.springmvc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 注册容器初始化完成的事件
 * 
 * @author LQ
 *
 */
public final class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		// 初始化 h2 数据库
		try (Connection connection = arg0.getApplicationContext().getBean(DataSource.class).getConnection()) {
			ScriptRunner scriptRunner = new ScriptRunner(connection);
			scriptRunner.runScript(Resources.getResourceAsReader("schema/schema.sql"));
			scriptRunner.runScript(Resources.getResourceAsReader("schema/data.sql"));
		} catch (SQLException | IOException e) {
			throw new RuntimeException(e);
		}
	}

}
